<template>
  <c-loading :loading="false">
    <view class="container">
      <c-search url="./search" transparent placeholder="输入关键词搜索"></c-search>
      <c-sort class="sort-wrap" @change="reload" v-model="state.sortField" v-model:desc="state.isDesc">
        <c-sort-item label="默认" value="" desc />
        <c-sort-item label="销量" value="sales" desc />
        <c-sort-item label="价格" value="salePrice" caret />
        <c-sort-item label="筛选" :active="!isEqual(defState, state)" alone icon="filter" @tap="showFilter = true" />
      </c-sort>
      <view class="goods-wrap">
        <goods-item v-for="item in list" :key="item.id" v-bind="item" @cart="onCart"></goods-item>
      </view>
      <c-pager v-bind="pager"></c-pager>
      <view class="fixed-btn-group">
        <view class="fixed-btn" hover-class="view-hover" @tap="router.push('./cart')">
          <c-badge :hide="!cartNum" :number="cartNum" offset-x="12rpx" offset-y="-12rpx">
            <image class="img" src="/assets/imgs/cart.png" />
          </c-badge>
        </view>
      </view>
    </view>
    <template #popup>
      <c-popup position="right" v-model="showFilter">
        <view class="filter-pop">
          <view class="filter-title">价格区间</view>
          <view class="flex input-group">
            <view class="grow"><input class="input" type="digit" v-model="state.minPrice" placeholder="最低价" /></view>
            <view class="shrink">-</view>
            <view class="grow"><input class="input"  type="digit" v-model="state.maxPrice" placeholder="最高价" /></view>
          </view>
          <view class="filter-title">品牌</view>
          <view class="tags">
            <view class="tag" :class="{ active: state.brandId == brand.value }" @tap="setValueId(brand.value, 'brandId')" v-for="brand in brandList" :key="brand.value">
              {{ brand.name }}
            </view>
          </view>
          <view class="filter-title">分类</view>
          <view class="tags">
            <view class="tag" v-for="cai in categories" @tap="setValueId(cai.id, 'categoryId')" :key="cai.id" :class="{ active: state.categoryId == cai.id }">
              {{ cai.categoryName }}
            </view>
          </view>
          <view class="flex-foot flex-center">
            <c-button size="inline" class="round" type="info" plain @tap="reset">重置</c-button>
            <c-button type="primary" size="inline" class="round" @tap="onFilter">筛选</c-button>
          </view>
        </view>
      </c-popup>
      <sku-popup v-model="showSku" v-bind="info ?? {}" btn-text="加入购物车" @confirm="onAddCart"></sku-popup>
    </template>
  </c-loading>
</template>
<script setup>
import { CLoading, CPager, CPopup, CSearch, CSort, CSortItem, CBadge, CButton } from '@/components';
import { afterLogin, useLoading, usePager, useRouter } from '@/hooks';
import { reactive, ref } from 'vue';
import { View, Input } from '@tarojs/components';
import goodsItem from './components/goods-item.vue';
import SkuPopup from './components/sku-popup.vue';
import api from '@/api';
import toast from '@/utils/toast';
import { useDidShow } from '@tarojs/taro';
import { extend } from '@/utils';
import { isEqual } from 'lodash';

const router = useRouter();
const defState = {
  sortField: '',
  categoryId: 0,
  brandId: '',
  minPrice: '',
  maxPrice: '',
  isDesc: false
};
const state = reactive(extend(true, {}, defState));
const showFilter = ref(false);
const showSku = ref(false);
const info = ref(null);
const cartNum = ref(0);
const brandList = ref([]);
const categories = ref([]);

const { pager, list, reload } = usePager({
  immediate: false,
  handler: (skip, take) =>
    api.goods.goodsGoodsUserList({
      ...state,
      skip,
      take
    })
});

useLoading(async options => {
  await afterLogin();
  if (options.cid) {
    state.categoryId = options.cid;
  } 
  if (options.bid) {
    state.brandId = options.bid;
  }
  brandList.value = await api.goods.goodsBrandOptions();
  categories.value = (await api.goods.goodsCategoryGetTree()).flatMap(a => a.children ?? [a]);
  reload();
});
const setValueId = (id, name) => {
  if (state[name] == id) {
    state[name] = '';
  } else {
    state[name] = id;
  }
};

const reset = () => {
  for (const key in defState) {
    state[key] = defState[key];
  }
};
const onFilter = () => {
  showFilter.value = false;
  reload();
};

const onCart = item => {
  toast.loading.lock(async () => {
    info.value = await api.goods.goodsGetDetail({ id: item.id });
    showSku.value = true;
  });
};
const loadCartCount = async () => {
  cartNum.value = await api.goods.cartCount();
};

const onAddCart = async ({ sku, qty }) => {
  await api.goods
    .cartAdd({
      id: sku.id,
      value: qty
    })
    .success('已加入您的购物车', true)
    .error();
  loadCartCount();
};
useDidShow(() => loadCartCount());
</script>
<style lang="scss">
.goods-wrap {
  padding: 20px 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.sort-wrap {
  padding: 0 20px;
}
.fixed-btn-group {
  position: fixed;
  right: 30px;
  bottom: calc(30px + var(--safe-bottom));
  .fixed-btn {
    border-radius: 50%;
    width: 72px;
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--color-caption);
    box-shadow: 0 0px 10px rgba(0, 0, 0, 0.1);
    font-size: 20px;
    .img {
      height: 42px;
      margin: 0 auto 2px;
      width: 42px;
    }
  }
}
.filter-pop {
  width: 620px;
  display: flex;
  justify-content: flex-end;
  flex-direction: column;
  padding: 0 5px 0 20px;
  .flex-foot {
    margin-top: 100px;
    padding-bottom: max(var(--safe-bottom), 30px);
    .c-btn {
      width: 200px;
    }
  }
  .input-group {
    align-items: center;
    .grow {
      border-radius: 30px;
      background-color: var(--color-background);
      padding: 0 16px;
      margin-bottom: 20px;
    }
    .shrink {
      padding: 0 30px;
    }
    .input {
      width: 100%;
      height: 60px;
      line-height: 60px;
      text-align: center;
    }
  }
  .filter-title {
    margin-top: 50px;
    margin-bottom: 30px;
  }
  .tags {
    display: flex;
    flex-wrap: wrap;
    margin-right: -20px;
    .tag {
      line-height: 60px;
      border-radius: 30px;
      font-size: 22px;
      padding: 0 20px;
      min-width: 180px;
      text-align: center;
      margin-right: 20px;
      margin-bottom: 20px;
      background-color: var(--color-background);
      &.active {
        --color-background: var(--color-primary);
        color: var(--color-caption);
      }
    }
  }
}
</style>
